<template>
  <div class="partner-form">
    <a-form
      ref="formRef"
      :model="form"
      :label-col-props="{ span: 4 }"
      :wrapper-col-props="{ span: 20 }"
      label-align="right"
    >
      <a-tabs type="card-gutter">
        <a-tab-pane key="basic" title="基本信息">
          <a-form-item
            field="realName"
            label="合伙人名称"
            :rules="[{ required: true, message: '请输入合伙人名称' }]"
          >
            <a-input
              v-model="form.realName"
              :placeholder="$t('请输入合伙人名称')"
              allow-clear
            />
          </a-form-item>

          <a-form-item
            field="source"
            label="合伙人类型"
            :rules="[{ required: true, message: '请选择合伙人类型' }]"
          >
            <a-radio-group v-model="form.source">
              <a-radio :value="PartnerTypeEnum.PERSONAL">加盟</a-radio>
              <a-radio :value="PartnerTypeEnum.ENTERPRISE">购买</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item filed="form.redirectPlatformLimit" label="转发平台数">
            <a-slider
              v-model="form.redirectPlatformLimit"
              :min="0"
              :max="5"
              :default-value="0"
              :style="{ width: '200px' }"
            />
          </a-form-item>
          <a-form-item
            field="enabled"
            label="状态"
            :rules="[{ required: true, message: '请选择状态' }]"
          >
            <a-switch v-model="form.enabled" type="round">
              <template #checked>启用</template>
              <template #unchecked>禁用</template>
            </a-switch>
          </a-form-item>

          <template v-if="!isEdit">
            <a-form-item
              field="username"
              label="登录用户名"
              :rules="[{ required: !isEdit, message: '请输入登录用户名' }]"
            >
              <a-input
                v-model="form.username"
                :placeholder="$t('请输入登录用户名')"
                allow-clear
              />
            </a-form-item>

            <a-form-item
              field="password"
              label="登录密码"
              :rules="[{ required: !isEdit, message: '请输入登录密码' }]"
            >
              <a-input-password
                v-model="form.password"
                :placeholder="$t('请输入登录密码')"
                allow-clear
              />
            </a-form-item>
          </template>

          <a-form-item
            field="mobile"
            label="手机号码"
            :rules="[
              { required: true, message: '请输入手机号码' },
              {
                match: /^1[3-9]\d{9}$/,
                message: '请输入正确的手机号码格式',
              },
            ]"
          >
            <a-input
              v-model="form.mobile"
              :placeholder="$t('请输入手机号码')"
              allow-clear
            />
          </a-form-item>

          <a-form-item
            v-if="form.partnerRole === PartnerRoleEnum.MANAGER"
            field="managerPartnerDivideRate"
            label="分佣比例"
            :rules="[
              {
                required: form.partnerRole === PartnerRoleEnum.MANAGER,
                message: '请输入分佣比例',
              },
            ]"
          >
            <a-input-number
              v-model="form.managerPartnerDivideRate"
              :min="0"
              :max="100"
              :precision="2"
              :step="0.1"
              mode="button"
              :placeholder="$t('请输入分佣比例')"
              style="width: 100%"
            >
              <template #append>%</template>
            </a-input-number>
          </a-form-item>

          <a-form-item field="nickName" label="昵称">
            <a-input
              v-model="form.nickName"
              :placeholder="$t('请输入昵称')"
              allow-clear
            />
          </a-form-item>

          <a-form-item field="remark" label="备注">
            <a-textarea
              v-model="form.remark"
              :placeholder="$t('请输入备注信息')"
              allow-clear
            />
          </a-form-item>
        </a-tab-pane>

        <a-tab-pane key="identification" title="身份信息">
          <a-form-item
            field="idCard"
            label="身份证号"
            :rules="[
              {
                match: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
                message: '请输入正确的身份证号码格式',
                trigger: 'blur',
              },
            ]"
          >
            <a-input
              v-model="form.idCard"
              :placeholder="$t('请输入身份证号')"
              allow-clear
            />
          </a-form-item>

          <a-form-item field="idCardPhotoPositive" label="身份证正面">
            <a-upload
              action="/api/upload"
              :file-list="idCardPositiveFileList"
              :limit="1"
              @change="handleIdCardPositiveChange"
              :custom-request="customUploadRequest"
            >
              <template #upload-button>
                <a-button>上传身份证正面照片</a-button>
              </template>
            </a-upload>
          </a-form-item>

          <a-form-item field="idCardPhotoBack" label="身份证反面">
            <a-upload
              action="/api/upload"
              :file-list="idCardBackFileList"
              :limit="1"
              @change="handleIdCardBackChange"
              :custom-request="customUploadRequest"
            >
              <template #upload-button>
                <a-button>上传身份证反面照片</a-button>
              </template>
            </a-upload>
          </a-form-item>

          <a-form-item field="headImage" label="头像">
            <a-upload
              action="/api/upload"
              :file-list="headImageFileList"
              :limit="1"
              @change="handleHeadImageChange"
              :custom-request="customUploadRequest"
              list-type="picture-card"
            >
              <div class="upload-picture-card-text">
                <div class="upload-picture-card-text-icon">
                  <icon-plus />
                </div>
                <div>上传头像</div>
              </div>
            </a-upload>
          </a-form-item>
        </a-tab-pane>
      </a-tabs>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, PropType, onMounted, computed } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import {
    addPartner,
    updatePartner,
    Partner,
    PartnerTypeEnum,
    PartnerRoleEnum,
    StatusEnum,
  } from '@/api/partner';
  import { IconPlus } from '@arco-design/web-vue/es/icon';
  import type { UploadItem } from '@arco-design/web-vue';

  const props = defineProps({
    formData: {
      type: Object as PropType<Partial<Partner>>,
      required: true,
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
  });

  const formRef = ref();
  const form = reactive<Partial<Partner>>({
    realName: '',
    mobile: '',
    username: '',
    password: '',
    source: PartnerTypeEnum.PERSONAL,
    partnerRole: PartnerRoleEnum.MARKET,
    redirectPlatformLimit: 0,
    enabled: true,
  });

  const idCardPositiveFileList = ref<UploadItem[]>([]);
  const idCardBackFileList = ref<UploadItem[]>([]);
  const headImageFileList = ref<UploadItem[]>([]);

  // 自定义上传
  const customUploadRequest = (options: any) => {
    const { onProgress, onSuccess, onError, fileItem, file } = options;

    // 这里应该调用真实的上传API，这里为了演示直接模拟成功
    // 模拟上传进度
    const interval = setInterval(() => {
      const percent = Math.floor(Math.random() * 10) + 10;
      onProgress(percent > 100 ? 100 : percent);
    }, 300);

    // 模拟上传完成
    setTimeout(() => {
      clearInterval(interval);
      // 模拟上传成功，返回文件URL
      const response = {
        data: {
          url: URL.createObjectURL(file),
        },
      };
      onSuccess(response);
    }, 1500);
  };

  // 处理身份证正面照片上传
  const handleIdCardPositiveChange = (fileList: UploadItem[]) => {
    idCardPositiveFileList.value = [...fileList];
    if (fileList.length > 0 && fileList[0].response) {
      form.idCardPhotoPositive = fileList[0].response.data.url;
    } else {
      form.idCardPhotoPositive = '';
    }
  };

  // 处理身份证反面照片上传
  const handleIdCardBackChange = (fileList: UploadItem[]) => {
    idCardBackFileList.value = [...fileList];
    if (fileList.length > 0 && fileList[0].response) {
      form.idCardPhotoBack = fileList[0].response.data.url;
    } else {
      form.idCardPhotoBack = '';
    }
  };

  // 处理头像上传
  const handleHeadImageChange = (fileList: UploadItem[]) => {
    headImageFileList.value = [...fileList];
    if (fileList.length > 0 && fileList[0].response) {
      form.headImage = fileList[0].response.data.url;
    } else {
      form.headImage = '';
    }
  };

  // 表单校验
  const validate = async () => {
    try {
      await formRef.value.validate();
      return true;
    } catch (error) {
      return false;
    }
  };

  // 提交表单
  const submit = async () => {
    try {
      // 构建提交数据
      const submitData: Partial<Partner> = { ...form };
      console.log('submitData', submitData);
      // 提交到服务器
      if (props.isEdit) {
        const res = await updatePartner(submitData);
        return res.data;
      }
      const res = await addPartner(submitData);
      return res.data;
    } catch (error) {
      console.error('提交表单失败:', error);
      Message.error('提交表单失败');
      return false;
    }
  };

  // 初始化表单数据
  onMounted(() => {
    // 填充表单数据
    if (props.formData) {
      Object.assign(form, props.formData);
    }

    // 初始化文件列表
    if (form.idCardPhotoPositive) {
      idCardPositiveFileList.value = [
        {
          uid: '1',
          name: '身份证正面.jpg',
          url: form.idCardPhotoPositive,
          status: 'done',
        },
      ];
    }

    if (form.idCardPhotoBack) {
      idCardBackFileList.value = [
        {
          uid: '2',
          name: '身份证反面.jpg',
          url: form.idCardPhotoBack,
          status: 'done',
        },
      ];
    }

    if (form.headImage) {
      headImageFileList.value = [
        {
          uid: '3',
          name: '头像.jpg',
          url: form.headImage,
          status: 'done',
        },
      ];
    }
  });

  // 暴露方法给父组件
  defineExpose({
    validate,
    submit,
  });
</script>

<style scoped lang="less">
  .partner-form {
    padding: 20px 0;
  }

  :deep(.arco-form-item-content-flex) {
    display: flex;
    align-items: center;
  }

  :deep(.arco-upload-picture-card) {
    width: 80px;
    height: 80px;
  }

  .upload-picture-card-text {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;

    &-icon {
      margin-bottom: 4px;
      font-size: 16px;
    }
  }
</style>
